package com.jason.kotlin.gank.ui

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.webkit.*
import android.widget.LinearLayout
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.jason.kotlin.gank.GankConstant
import com.jason.kotlin.gank.R
import com.jason.library.widget.snackbar.MySnackbar

class WebActivity : AppCompatActivity() {

    lateinit var toolbar: Toolbar

    lateinit var webView: WebView

    lateinit var progressbar: ProgressBar

    lateinit var rootView: LinearLayout

    //标题
    private var flagTitle: String? = null
    private var titleContent: String? = null
    private var url: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.gank_activity_web)

        initView()

        initIntent()

        initMyToolBar()

        initWebView()
    }

    private fun initView() {
        toolbar = findViewById(R.id.toolbar)
        webView = findViewById(R.id.webView)
        progressbar = findViewById(R.id.progressbar)
        rootView = findViewById(R.id.rootView)
    }

    private fun initMyToolBar() {
        val title = if (TextUtils.isEmpty(flagTitle)) {
            titleContent!!
        } else {
            "$flagTitle+$titleContent"
        }

        toolbar.title = title // 标题的文字需在setSupportActionBar之前，不然会无效
        toolbar.setNavigationIcon(R.drawable.ic_back_white)

        setSupportActionBar(toolbar)
        toolbar.setTitleTextColor(resources.getColor(R.color.white))

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_web, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> finish()
            R.id.action_copy -> copy(url)
            R.id.action_open -> openBrowser(url)
            R.id.action_share -> MySnackbar.makeSnackBarBlue(toolbar, "分享功能开发中")
            /* IntentUtils.startAppShareText(
                this@WebActivity,
                "GankMM链接分享",
                "GankMM链接分享：$url"
            )*/
        }
        return super.onOptionsItemSelected(item)
    }

    private fun initIntent() {
        flagTitle = intent.getStringExtra(GankConstant.WEB_TITLE_FLAG)
        titleContent = intent.getStringExtra(GankConstant.WEB_TITLE)
        url = intent.getStringExtra(GankConstant.WEB_URL)
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        //设置背景色
        webView.setBackgroundColor(0)
        //设置WebView属性，能够执行Javascript脚本
        webView.settings.javaScriptEnabled = true
        webView.settings.allowFileAccess = true
        // 开启DOM storage API 功能
        webView.settings.domStorageEnabled = true
        // 开启database storage API功能
        webView.settings.databaseEnabled = true
        webView.settings.defaultTextEncodingName = "UTF-8"
        //自适应屏幕
        webView.settings.useWideViewPort = true
        webView.settings.loadWithOverviewMode = true
        // 设置可以支持缩放
        webView.settings.setSupportZoom(true)
        webView.settings.builtInZoomControls = true
        //不显示webview缩放按钮
        webView.settings.displayZoomControls = false
        //设置缩放比例：最小25
        webView.setInitialScale(100)
        // 建议缓存策略为，判断是否有网络，有的话，使用LOAD_DEFAULT,无网络时，使用LOAD_CACHE_ELSE_NETWORK
//        if (NetworkUtils.isConnected) {
//            webView.settings.cacheMode = WebSettings.LOAD_DEFAULT // 根据cache-control决定是否从网络上取数据。
//        } else {
//            webView.settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK //优先加载缓存
//        }

        //////////////////////////////
        webView.loadUrl(url!!)
        //设置了默认在本应用打开，不设置会用浏览器打开的
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                val hitTestResult = view.hitTestResult
                //hitTestResult==null解决重定向问题
                if (!TextUtils.isEmpty(url) && hitTestResult == null) {
                    view.loadUrl(url)
                    return true
                }
                return super.shouldOverrideUrlLoading(view, url)
            }

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                Log.i("chenby","url = $url")

            }

            override fun onReceivedError(
                view: WebView,
                request: WebResourceRequest,
                error: WebResourceError
            ) {
                super.onReceivedError(view, request, error)
                Log.i("chenby","onReceivedError")
            }
        }
        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                if (newProgress == 100) {
                    // 网页加载完成
                    progressbar.visibility = View.GONE
                } else {
                    // 加载中
                    if (progressbar.visibility == View.GONE) {
                        progressbar.visibility = View.VISIBLE
                    }
                    progressbar.progress = newProgress
                }
            }
        }
        webView.setDownloadListener { url, _, _, _, _ ->
            val uri = Uri.parse(url)
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
        }
    }


    override fun onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()
            return
        }
        super.onBackPressed()
    }

    override fun onResume() {
        super.onResume()
        webView.onResume()
    }

    override fun onPause() {
        super.onPause()
        webView.onPause()
        //保证了webView退出后不再有声音
        webView.reload()
    }


    override fun onDestroy() {
        webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
        rootView.removeView(webView)
        webView.destroy()
        super.onDestroy()
    }


    fun showToast(msg: String?) {
        MySnackbar.makeSnackBarBlack(toolbar, msg)
    }

    fun copy(string: String?) {
        // 从API11开始android推荐使用android.content.ClipboardManager
        val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 将文本内容放到系统剪贴板里。
        val clipData = ClipData.newPlainText("text", string)
        cm.setPrimaryClip(clipData)
        MySnackbar.makeSnackBarBlack(toolbar, "复制成功")
    }

    fun openBrowser(url: String?) {
        val intent = Intent()
        intent.action = "android.intent.action.VIEW"
        val content_url = Uri.parse(url)
        intent.data = content_url
        startActivity(intent)
    }

}